'''
Created on Dec 12, 2012

@author: peng
'''
import os
import base64
import MySQLdb
import datetime
import TrackProtos_pb2

_DB_CONFIG = {
    'host': '10.135.25.117',
    'user': 'track',
    'password': 'P@55w0rd',
    'db': 'appchannel',
    'port': 3306
}

_FILE_PATH = '/var/app/log/datatrack-service'

# exclude android system apps
_EXCLUDED_PAGENAME = [
    'android',
    'com.andrew.apollo',
    'com.android.apps.tag',
    'com.android.backupconfirm',
    'com.android.bluetooth',
    'com.android.browser',
    'com.android.calculator2',
    'com.android.calendar',
    'com.android.certinstaller',
    'com.android.connection',
    'com.android.contacts',
    'com.android.defcontainer',
    'com.android.deskclock',
    'com.android.development',
    'com.android.email',
    'com.android.exchange',
    'com.android.galaxy4',
    'com.android.gallery3d',
    'com.android.htmlviewer',
    'com.android.inputdevices',
    'com.android.inputmethod.latin',
    'com.android.keychain',
    'com.android.magicsmoke',
    'com.android.mms',
    'com.android.musicvis',
    'com.android.nfc',
    'com.android.noisefield',
    'com.android.packageinstaller',
    'com.android.phasebeam',
    'com.android.phone',
    'com.android.providers.applications',
    'com.android.providers.calendar',
    'com.android.providers.contacts',
    'com.android.providers.downloads',
    'com.android.providers.downloads.ui',
    'com.android.providers.drm',
    'com.android.providers.media',
    'com.android.providers.settings',
    'com.android.providers.telephony',
    'com.android.providers.userdictionary',
    'com.android.provision',
    'com.android.quicksearchbox',
    'com.android.settings',
    'com.android.sharedstoragebackup',
    'com.android.smspush',
    'com.android.soundrecorder',
    'com.android.spare_parts',
    'com.android.stk',
    'com.android.systemui',
    'com.android.videoeditor',
    'com.android.voicedialer',
    'com.android.vpndialogs',
    'com.android.wallpaper',
    'com.android.wallpaper.holospiral',
    'com.android.wallpaper.livepicker'
]


class MySQLdbWrapper:
    '''MySQL wrapper'''
    conn = None

    def connect(self):
        self.conn = MySQLdb.connect(host=_DB_CONFIG['host'],
                                    user=_DB_CONFIG['user'],
                                    passwd=_DB_CONFIG['password'],
                                    db=_DB_CONFIG['db'],
                                    port=_DB_CONFIG['port'])
        self.conn.set_character_set('utf8')
        self.conn.autocommit(True)

    def cursor(self):
        try:
            self.connect()
            return self.conn.cursor(MySQLdb.cursors.DictCursor)
        except MySQLdb.OperationalError, e:
            print e
            self.connect()
            return self.conn.cursor(MySQLdb.cursors.DictCursor)

_db = MySQLdbWrapper()


def _get_data(sql_list):
    try:
        cursor = _db.cursor()
        sql = ' '.join(sql_list)
        print sql
        cursor.execute(sql)
        data = cursor.fetchall()
        return data
    finally:
        cursor.close()


def yesterday():
    return (datetime.datetime.now() - datetime.timedelta(days=1)).strftime(\
                '%Y-%m-%d')


def main():
    '''main process'''
    sql_list = []
    sql_list.append("SELECT data FROM report_raw_track_data")
    sql_list.append("WHERE DATE(created_at)='%s'" % \
                        yesterday())
    raw_data = _get_data(sql_list)
    for row in raw_data:
        track_data = _do_parse(row['data'])
        _log_data(track_data)


def _do_parse(raw_data):
    '''parse raw data'''
    serialized_data = base64.b64decode(raw_data)
    track_data = TrackProtos_pb2.TrackData()
    track_data.ParseFromString(serialized_data)
    return track_data


def _log_data(track_data):
    '''log data to files'''
    file_path = _FILE_PATH
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    file_full_path = None
    # new install
    if track_data.message_type == track_data.INSTALLATION:
        file_full_path = os.path.join(file_path, 'appstore-new_installed.log')
    # all apps
    elif track_data.message_type == track_data.APP_LIST:
        file_full_path = os.path.join(file_path, 'appstore-all_installed.log')
    # uninstall
    elif track_data.message_type == track_data.UNINSTALLATION:
        file_full_path = os.path.join(file_path, 'appstore-uninstalled.log')
    # uninstall
    elif track_data.message_type == track_data.INSTALLATION_FAILURE:
        file_full_path = os.path.join(file_path,
                                      'appstore-uninstall-failed.log')

    if not file_full_path:
        return

    with open(file_full_path, 'w+') as f:
        for app in track_data.apps:
            if app.package_name in _EXCLUDED_PAGENAME:
                continue
            f.write(app.package_name + '\n')


if __name__ == '__main__':
    main()
